package com.hmall.order.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hmall.common.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO
 *
 * @Author whx
 * @Date 2024/11/15 20:28
 */
@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("authorization");

        if(!StrUtil.isEmpty(userId)){
            ThreadLocalUtil.setCurrentId(Long.valueOf(userId));
            log.info("userId：" + userId);

            return true;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.removeCurrentId();
    }
}
